"use strict";
import axios from "axios";
import { log } from "@/utils";
import store from "@/store";
import router from "@/router";

// 创建axios实例
export function createAxios(opt = {}) {
  const service = axios.create({
    baseURL: opt.baseURL,
    timeout: 30000
  });

  // TODO 拦截器需要根据项目改造
  const ignoreTokenUrls = ["/api/v1/auth/login"];
  service.interceptors.request.use(
    (config) => {
      config.headers["terrace"] = process.env.VUE_APP_TERRACE;
      if (store.getters.token) {
        config.headers[process.env.VUE_APP_TOKEN_KEY] = store.getters.token;
      }

      if (store.getters.projectId) {
        config.headers["projectId"] = store.getters.projectId;
        if (config.data && !config.data.projectId) {
          config.data.projectId = store.getters.projectId;
        }
      }

      if (ignoreTokenUrls.indexOf(config.url) === -1) {
        if (!store.getters.token && router.currentRoute.path !== "/login") {
          router.replace("/login");
        }
      }
      return config;
    },
    (error) => {
      log(error);
      return Promise.reject(error);
    }
  );

  const ErrorCodes = [1001, 1012];
  service.interceptors.response.use(
    (response) => {
      if (response.config.responseType === "blob") {
        let name = response.headers["content-disposition"] || "";
        let ret = name.match(/filename=([^;]*)/);
        response.filename = decodeURIComponent((ret && ret[1]) || "blob");
        return response;
      }
      const res = response.data;
      if (response.status === 403 || ErrorCodes.indexOf(res.retcode) > -1) {
        router.replace("/login");
        return Promise.reject({ msg: res.msg || "登录信息失效" });
      } else if (res.retcode && res.retcode !== 0) {
        return Promise.reject(new Error(res.msg || "Error"));
      } else {
        return res;
      }
    },
    (error) => {
      log("err" + error); // for debug
      return Promise.reject(error);
    }
  );

  return service;
}

export default createAxios({
  baseURL: "/API"
});
